package com.iakuil.app.common.ws;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;

/**
 * WebSocket配置
 *
 * <p>测试地址：ws://localhost:10240/wsapi?uid=xxx
 *
 * @author Kai
 */
@AutoConfiguration
@EnableWebSocket
public class WebSocketAutoConfiguration implements WebSocketConfigurer {

    private final RedisTemplate<String, Object> redisTemplate;

    @Value("${app.ws.endpoint:/wsapi/**}")
    private String endpoint;

    public WebSocketAutoConfiguration(RedisTemplate<String, Object> redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    @Override
    public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
        registry.addHandler(defaultMessageHandler(), endpoint).addInterceptors(new WsHandshakeInterceptor()).setAllowedOrigins("*");
    }

    /**
     * 用户私聊消息处理
     *
     * <p>私聊消息示例：{"to":"xxx-xxx-xxx", "content":"hey~"}
     */
    @Bean
    @ConditionalOnMissingBean
    public WebSocketHandler defaultMessageHandler() {
        return new UserMessageHandler(redisTemplate);
    }
}
